package ar.com.fracervellera.web.controller;


import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.com.fracervellera.model.PMF;
import ar.com.fracervellera.model.Project;
import ar.com.fracervellera.server.services.ProjectService;
import ar.com.fracervellera.server.services.ProjectServiceImp;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.repackaged.org.json.JSONArray;



public class ProjectSlideShowController extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private PersistenceManager pm ;
	private ProjectService projectService = ProjectServiceImp.GetInstance();
	private ProjectServiceImp slideShow = ProjectServiceImp.GetInstance();
	private static final Logger log = Logger.getLogger("GooglePrivateClaendarService");
	

	@Override
	public void init() throws ServletException {
		super.init();
		pm = PMF.get().getPersistenceManager();
		
	}
	
	@Override
	public void destroy() {
		super.destroy();
		if(pm != null && !pm.isClosed()){
			pm.close();
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		List<Project> projectList = projectService.getLastProjects(pm);
		JSONArray response = new JSONArray();		
		
		for(Project current : projectList) {
			log.warning(" exist eun proyecto " + current.getTitle());
			response.put(current.toJson());
		}
		resp.setContentType("text/json");
		resp.getWriter().append(response.toString());

	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String blobKey = req.getParameter("blobKey");
		byte[] ans;
		if(blobKey != null && !blobKey.isEmpty()) {
			//TODO: put some enums for all the size that the web layout support.
			ans = slideShow.getFixedImage(new BlobKey(blobKey),440, 320);
			resp.setContentType("image/png");
			resp.getOutputStream().write(ans);
			resp.getOutputStream().flush();
			resp.getOutputStream().close();
		}
	}
}
